﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using MobiSms.Library.Helpers;
using System.Xml.Linq;

namespace MobiSms.ViewModel
{
    public class LogViewModel : ViewModelBase
    {
        public ObservableCollection<LogInfo> ItemsOfLogs
        {
            get
            {
                if (IsDesignMode)
                {
                    return null;
                }
                else
                {
                    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (store.FileExists("log.xml"))
                        {
                            using (IsolatedStorageFileStream isoFileStream = store.OpenFile("log.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                XDocument document = XDocument.Load(isoFileStream, LoadOptions.None);
                                IEnumerable<LogInfo> items = (from item in document.Descendants("log")
                                                              select new LogInfo(item.Element("type").Value, item.Element("message").Value, item.Element("trace").Value)
                                                              {
                                                                  Time = DateTime.Parse(item.Element("time").Value)
                                                              });

                                return new ObservableCollection<LogInfo>(items);
                            }
                        }
                        return null;
                    }
                }
            }
        }
    }
}
